import { defineStore } from "pinia";
import {
  loginlogin,
  loginlogindata,
  registergetGradeSubject,
} from "@/api/user";
import { setToken, clearToken, setPermission, subject } from "@/utils/auth";
// import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from "./types";
// 从 localStorage 中获取 SubjectID
let storedSubjectID = localStorage.getItem("SubjectID");
// const storedPermission = JSON.parse(localStorage.getItem("permission"));
// if (storedPermission) {
//   if (storedPermission.subjectIds.length > 0) {
//       storedSubjectID = storedPermission.subjectIds[0];
//   }
// }
// console.log('storedSubjectID',storedSubjectID);
const useUserStore = defineStore("user", {
  state: (): UserState => ({
    // name: undefined,
    // avatar: undefined,
    index: "",
    subjectID: storedSubjectID ? storedSubjectID : undefined,
    GradeID: undefined,
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    setSubjectID(value: string | undefined) {
      this.subjectID = value;
    },
    async login(loginForm: loginlogindata) {
      try {
        const res = await loginlogin(loginForm);
        setToken(res.code);
        setPermission(res);
        subject(res.subjectIds);

        registergetGradeSubject({ gid: res.GradeID }).then((res) => {
          localStorage.setItem("SubjectID", res.sub[1].SubjectID);
          this.subjectID = res.sub[1].SubjectID;
          // res.sub.forEach((item) => {
          //   item. SubjectID
          // });
          
        });
        // this.GradeID=res.GradeID
        if (res.GradeID !== undefined) {
          this.GradeID = res.GradeID;
        }
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    //   //学科验证
    // subject(){

    // },
  },
});

export default useUserStore;
